package com.geeyuu.android.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

import com.geeyuu.android.GeeApplication;
import com.geeyuu.android.R;
import com.geeyuu.android.databases.DataBaseHelper;
import com.geeyuu.android.service.DataKey;
import com.geeyuu.android.service.ProtocolCommand;
import com.geeyuu.android.utils.AndroidUtil;
import com.geeyuu.android.utils.CommonUtil;

public class LoginActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.TAG = "LoginActivity";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);

        GeeApplication geeApplication = (GeeApplication) getApplication();
        geeApplication.addActivity(LoginActivity.this);

        initTitleBar();
        initViews();
        
        startBindService();
        
    }
    
    @Override
    protected void onDestroy() {
        stopBindService();
        super.onDestroy();
    }
    
    @Override
    public void onBackPressed() {
        DataBaseHelper.close();
        super.onBackPressed();
    }

    @Override
    protected void onReceiveMsgFromService(int cmd, Bundle bundle, boolean isMsgNormal) {
        switch (cmd) {
        case ProtocolCommand.CMD_LOGIN:
            cancelProgressDialog();
            if(isMsgNormal){
                Intent intent = new Intent(LoginActivity.this, MainTabActivity.class);
                startActivity(intent);
                GeeApplication geeApplication = (GeeApplication) getApplication();
                geeApplication.clearActivities();
            }else{
                AndroidUtil.showToast(getApplicationContext(), "登录失败，请重试");
            }
            break;

        case ProtocolCommand.CMD_REGISTER:
            if(isMsgNormal){
                //游客注册正常返回，现在发送游客登录
                //发送登录请求
                Bundle loginBundle = new Bundle();
                loginBundle.putString(DataKey.S_KEY_LOGIN_TYPE, DataKey.S_VALUE_LOGIN_TYPE_NORMAL);
                loginBundle.putString(DataKey.S_KEY_IS_GUEST, DataKey.S_VALUE_REGISTER_IS_GUEST);
                sendMsgToService(ProtocolCommand.CMD_LOGIN, loginBundle);
            }else{
                cancelProgressDialog();
                AndroidUtil.showToast(getApplicationContext(), "登录失败，请重试");
            }
            break;
        }
    }
    
    private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.top_right_button:
                Intent intent2 = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent2);
                break;
                
            case R.id.login_button: //普通登录
                if (CommonUtil.isEmpty(currentAccount) || CommonUtil.isEmpty(currentPwd)) {
                    AndroidUtil.showToast(getApplicationContext(), "账号或者密码不能为空");
                    return;
                }
                if (currentAccount.length() > 30) {
                    AndroidUtil.showToast(getApplicationContext(), "账号长度30个字符以内");
                    return;
                }
                if (currentPwd.length() < 6 || currentPwd.length() > 30) {
                    AndroidUtil.showToast(getApplicationContext(), "密码长度6-30");
                    return;
                }
                if (!CommonUtil.isEmail(currentAccount)) {
                    AndroidUtil.showToast(getApplicationContext(), "请输入正确的邮箱");
                    return;
                }
                showProgressDialog("正在登录", "奋力登录中,请稍等...!", false);
                AndroidUtil.unlogin(LoginActivity.this);
                // 发送登录请求
                Bundle loginBundle = new Bundle();
                loginBundle.putString(DataKey.S_KEY_LOGIN_TYPE, DataKey.S_VALUE_LOGIN_TYPE_NORMAL);
                loginBundle.putString(DataKey.S_KEY_LOGIN_ACCOUNT, currentAccount);
                loginBundle.putString(DataKey.S_KEY_LOGIN_PASSWORD, currentPwd);
                loginBundle.putString(DataKey.S_KEY_IS_GUEST, DataKey.S_VALUE_REGISTER_IS_NOT_GUEST);
                sendMsgToService(ProtocolCommand.CMD_LOGIN, loginBundle);
                break;
            
            case R.id.guest_login_button: //游客登录，也是先注册后登录
                showProgressDialog("正在登录", "奋力登录中,请稍等...!", false);
                AndroidUtil.unlogin(LoginActivity.this);
                // 发送注册请求
                Bundle bundle = new Bundle();
                bundle.putString(DataKey.S_KEY_IS_GUEST, DataKey.S_VALUE_REGISTER_IS_GUEST);
                sendMsgToService(ProtocolCommand.CMD_REGISTER, bundle);
                break;
            }
        }
    };

    private void initTitleBar() {
        Button topLeftButton = (Button)findViewById(R.id.top_left_button);
        ViewGroup.LayoutParams vl = topLeftButton.getLayoutParams();
        vl.width = ViewGroup.LayoutParams.WRAP_CONTENT;
        topLeftButton.setLayoutParams(vl);
    }
    
    private String currentAccount = "";
    private String currentPwd = "";

    private void initViews() {
        findViewById(R.id.login_button).setOnClickListener(mOnClickListener);

        Button topRight = (Button) findViewById(R.id.top_right_button);
        topRight.setText("注册");
        topRight.setVisibility(View.VISIBLE);
        topRight.setOnClickListener(mOnClickListener);
        topRight.setBackgroundColor(Color.TRANSPARENT);
        topRight.setCompoundDrawablesWithIntrinsicBounds(R.drawable.vertical_line, 0, 0, 0);
        
        Button topLeft = (Button) findViewById(R.id.top_left_button);
        topLeft.setText("登录");
        topLeft.setVisibility(View.VISIBLE);
        topLeft.setBackgroundColor(Color.TRANSPARENT);
        topLeft.setCompoundDrawablesWithIntrinsicBounds(R.drawable.login_sign_icon, 0, 0, 0);
        
        findViewById(R.id.guest_login_button).setOnClickListener(mOnClickListener);
        
        final EditText etAccount = (EditText) findViewById(R.id.email);
        final EditText etPassword = (EditText) findViewById(R.id.password);
        setEditTextPasswordMode(etPassword, true);

        TextWatcher accountWatcher = new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                currentAccount = s.toString();
                if (null != currentAccount && currentAccount.length() > 0) {
                    currentAccount.trim().replace(" ", "");
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        };
        TextWatcher pwdWatcher = new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                currentPwd = s.toString();
                if (null != currentPwd && currentPwd.length() > 0) {
                    currentPwd.trim().replace(" ", "");
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        };

        etAccount.addTextChangedListener(accountWatcher);
        etPassword.addTextChangedListener(pwdWatcher);

        CheckBox checkbox = (CheckBox) findViewById(R.id.show_pwd);
        checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setEditTextPasswordMode(etPassword, isChecked);
            }
        });

    }
    
    private void setEditTextPasswordMode(EditText editText, boolean isChecked) {
        if (isChecked) {
            editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            editText.setSelection(currentPwd.length());
        } else {
            editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            editText.setSelection(currentPwd.length());
        }
    }

}
